<template>
  <div>
    <h2>家属管理</h2>
    <el-button type="primary" @click="openAdd()">新增家属</el-button>
    <el-table :data="tableData" row-key="familyId">
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="relationship" label="关系" />
      <el-table-column prop="elderName" label="关联老人" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="openEdit(row)">编辑</el-button>
          <el-button type="danger" @click="del(row.familyId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="show" :title="isAdd ? '新增家属' : '编辑家属'">
      <el-form :model="form" label-width="100px">
        <el-form-item label="姓名"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="电话"><el-input v-model="form.phone" /></el-form-item>
        <el-form-item label="关系"><el-input v-model="form.relationship" /></el-form-item>
        <el-form-item label="老人ID"><el-input v-model.number="form.elderId" /></el-form-item>
        <el-form-item label="登录名">
          <el-input v-model="form.loginName" placeholder="默认用手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getFamilyPage, addFamily, updateFamily, deleteFamily } from '@/api/family'

const tableData = ref([])
const show = ref(false)
const isAdd = ref(true)
const form = ref({})

const load = async () => {
  const res = await getFamilyPage({ current: 1, size: 10 })
  tableData.value = res.data.records
}

const openAdd = () => {
  form.value = {
    name: '',
    phone: '',
    relationship: '',
    elderId: '',
    loginName: ''   // 提交前会自动用手机号填充
  }
  isAdd.value = true
  show.value = true
}

const openEdit = (row) => {
  form.value = { ...row }
  isAdd.value = false
  show.value = true
}

const submit = async () => {
  // 容错：没填登录名 → 默认用手机号
  if (!form.value.loginName?.trim()) {
    form.value.loginName = form.value.phone
  }
  isAdd.value ? await addFamily(form.value) : await updateFamily(form.value)
  ElMessage.success(isAdd.value ? '新增成功' : '修改成功')
  show.value = false
  load()
}

const del = async (id) => {
  await deleteFamily(id)
  load()
}

onMounted(load)
</script>
